package com.sscw.tcp.tcp;

import com.sscw.tcp.dao.GConfDeviceDAO;
import com.sscw.tcp.constant.TcpCommandCodeConstant;
import com.sscw.tcp.mqtt.MQTTProducer;
import com.sscw.tcp.utils.TcpUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

@Slf4j
@Component
public class TcpServer implements ApplicationRunner {

    @Value("${server.tcp.port}")
    private Integer port;

    @Resource
    private MQTTProducer messageProducer;
    @Resource
    private GConfDeviceDAO gConfDeviceDAO;
    @Resource
    private RedissonClient redissonClient;

//    ThreadPoolExecutor executor = new ThreadPoolExecutor(30, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());


    @Override
    public void run(ApplicationArguments args) throws Exception {
        ServerSocket server = new ServerSocket(port);
        new Thread(() -> {
            while (true) {
                try {
                    log.info("TCP服务已创建：{}", server);
                    Socket socket = server.accept();
                    log.info("接收到客户端连接：{}", socket);
                    TcpListenerThread thread = new TcpListenerThread(socket, messageProducer, gConfDeviceDAO, redissonClient);
                    thread.start();
                    TcpUtils.sendMessage(socket, TcpCommandCodeConstant.GET_DEVICE_NO);
                } catch (IOException e) {
                    log.error("处理TCP连接异常：{}", e);
                }
            }
        }).start();
    }
}
